package service

import (
	"context"
	"demo/api/dto/request"
	"demo/api/dto/response"
	"demo/domain/model"
	"demo/domain/model/vo"
	"demo/infra/common/utils"
	"demo/infra/errors"
)

type UrlQueryService struct {
	vsRepo model.VisitStatisticsRepository
	umRepo model.UrlMapRepository
}

// NewUrlQueryService 构造函数
func NewUrlQueryService(vsRepo model.VisitStatisticsRepository, umRepo model.UrlMapRepository) *UrlQueryService {
	return &UrlQueryService{vsRepo: vsRepo, umRepo: umRepo}
}

// UrlMapPageQuery 应用层处理用例：查询并转换为DTO
func (uqs *UrlQueryService) UrlMapPageQuery(ctx context.Context, req request.UrlMapPageMapRequest) ([]response.UrlMapPageResponse, int64, error) {
	// 1. DTO -> 领域查询对象（应用层负责）
	query := vo.UrlMapPageMapCondition{
		ShortUrl:    req.ShortUrl,
		LongUrl:     req.LongUrl,
		Description: req.Description,
		Editor:      req.Editor,
		Creator:     req.Creator,
		Source:      req.Source,
		PageNum:     req.PageNum,
		PageSize:    req.PageSize,
	}
	// 2. 调用仓储获取领域实体（依赖抽象）
	entities, total, err := uqs.umRepo.PageFindByCondition(ctx, &query)
	if err != nil {
		return nil, 0, err
	}
	// 3. 领域实体 -> DTO（应用层负责转换）
	return uqs.convertToShortUrlMapPageResponse(entities), total, nil
}

// UrlStatistics 应用层处理用例：查询并转换为DTO
func (uqs *UrlQueryService) UrlStatistics(ctx context.Context, req request.ShortUrlStatisticsRequest) ([]response.ShortUrlStatisticsResponse, int64, error) {
	// 1. DTO -> 领域查询对象（应用层负责）
	urlMap, err := uqs.umRepo.FindById(ctx, req.ShortUrlId)
	if err != nil {
		panic(errors.NewBizError("B0000", "短链不存在"))
	}
	query := vo.ShortUrlStatisticsCondition{
		CompressCode:        urlMap.CompressCode,
		StartStatisticsDate: req.StartStatisticsDate,
		EndStatisticsDate:   req.EndStatisticsDate,
		PageNum:             req.PageNum,
		PageSize:            req.PageSize,
	}
	// 2. 调用仓储获取领域实体（依赖抽象）
	entities, total, err := uqs.vsRepo.StatisticsByCondition(ctx, &query)
	if err != nil {
		return nil, 0, err
	}
	// 3. 领域实体 -> DTO（应用层负责转换）
	return uqs.convertToShortUrlStatisticsResponse(entities), total, nil
}

// convertToShortUrlStatisticsResponse 领域实体到DTO的转换（应用层核心职责）
func (uqs *UrlQueryService) convertToShortUrlStatisticsResponse(entities []vo.ShortUrlStatisticsResult) []response.ShortUrlStatisticsResponse {
	var results []response.ShortUrlStatisticsResponse
	for _, e := range entities {
		results = append(results, response.ShortUrlStatisticsResponse{
			StatisticsDate:              utils.FromTime(e.StatisticsDate).ForceDate(),
			LongUrl:                     e.LongUrl,
			PvCount:                     e.PvCount,
			UvCount:                     e.UvCount,
			IpCount:                     e.IpCount,
			EffectiveRedirectionCount:   e.EffectiveRedirectionCount,
			IneffectiveRedirectionCount: e.IneffectiveRedirectionCount,
		})
	}
	return results
}

// convertToDTO 领域实体到DTO的转换（应用层核心职责）
func (uqs *UrlQueryService) convertToShortUrlMapPageResponse(entities []vo.UrlMapPageResult) []response.UrlMapPageResponse {
	var results []response.UrlMapPageResponse
	for _, e := range entities {
		results = append(results, response.UrlMapPageResponse{
			ID:          e.ID,
			Description: e.Description,
			LongUrl:     e.LongUrl,
			ShortUrl:    e.ShortUrl,
			Creator:     e.Creator,
			Editor:      e.Editor,
			CreateTime:  utils.FromTime(e.CreateTime),
			EditTime:    utils.FromTime(e.EditTime),
		})
	}
	return results
}
